package ni;

import controller.*;
import chatsystemTDa2.*;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Observable;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * This class handles the interface with the network: sending and receiving messages
 */
public class ChatNI {
	
	/**
	 * link to the controller
	 */
	private ChatController chatController;
	private UDPSender sender;
	private UDPReceiver receiver;
	private TCPSender TCPsender;
	private TCPReceiver TCPreceiver;
	
	/**
	 * @param chatController is a link to the controller
	 * @param listMsg is a link to the queue of messages to send
	 */
	public ChatNI(ChatController chatController, LinkedBlockingQueue <Msg> listMsg){
		this.chatController = chatController;
        this.sender = new UDPSender(this, listMsg);
		this.receiver = new UDPReceiver(this);
		//this.TCPsender = new TCPSender(this);
		//this.TCPreceiver = new TCPReceiver(this);
	}
	
	/**
	 * starts the reception of a file
	 */
	public void receiveFile(){
		this.TCPreceiver.start();
	}
	
	/**
	 * closes the TCPReceiver thread
	 */
	public void stopFile(){
		this.TCPreceiver.close();
	}
	
	/**
	 * starts UDPSender and UDPReceiver threads
	 */
	public void start(){
		this.sender.start();
		this.receiver.start();
	}
	
	/**
	 * sends the treatment of the received message to the controller
	 * @param m is a message (message and ip address)
	 */
	public void process_receive(Msg m){
		this.chatController.process_receive(m);	
	}

	/**
	 * closes UDPSender and UDPReceiver threads
	 */
	public void close(){
		this.sender.close();
		this.receiver.close();
		//stopFile();
	}
}
